/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gestionmagasins_avec_patterns.forms;

import gestionmagasins_avec_patterns.GestionMagasinsMain;
import gestionmagasins_avec_patterns.model.CatalogueRoles;
import gestionmagasins_avec_patterns.model.CatalogueUsagers;
import gestionmagasins_avec_patterns.model.Role;
import gestionmagasins_avec_patterns.model.Usager;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ManageUsersJFrame extends CustomJFrame 
{

    private final DefaultListModel<Usager> usersListModel;
    private final ItemChangeListener roleSelectionChange;
    private Usager selectedUser;
    private boolean mustSave;
    private boolean isNewUser;
    
    /**
     * Creates new form ManageUsersJFrame
     */
    ManageUsersJFrame(MainMenuJFrame mainMenu, Usager usager) 
    {
        super(mainMenu, usager);
        
        initComponents();
        this.initKeyListeners();
        
        roleSelectionChange = new ItemChangeListener();
        selectedUser = null;
        mustSave = false;
        isNewUser = false;
        
        //Initialition des GroupBox
        userDetailsJPanel.setBorder(BorderFactory.createTitledBorder("Identification"));
        userPasswordJPanel.setBorder(BorderFactory.createTitledBorder("Modification de mot de passe"));

        //Initialisation du TextChangedListener de la recherche
        userSearchJText.getDocument().addDocumentListener(searchDocumentListener);
        
        //Initialisation de la liste d'usager
        usersListModel = new DefaultListModel<>();
        usersJList.setModel(usersListModel);

        //Affichage de tout les usagers
        for(Usager u : CatalogueUsagers.getInstance().getAll())
            usersListModel.addElement(u);
        
        usersJList.addListSelectionListener(listSelectItemListener);
        
        userSelected(null, false);
        
        //Initialisation de la liste de roles
        DefaultComboBoxModel rolesComboBoxModel = new DefaultComboBoxModel<>();
        roleJComboBox.setModel(rolesComboBoxModel);
        
        for(Role r : CatalogueRoles.getInstance().getRoles())
            rolesComboBoxModel.addElement(r);
    }
    
    @Override
    protected void formClosing()
    {
        if(verifySaveStatus())
        {
            super.formClosing();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        userSearchJText = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        usersJList = new javax.swing.JList();
        userDetailsJPanel = new javax.swing.JPanel();
        firstnameJText = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        lastnameJText = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        usernameJText = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        emailJText = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        roleJComboBox = new javax.swing.JComboBox();
        jLabel15 = new javax.swing.JLabel();
        newUserJButton = new javax.swing.JButton();
        saveUserJButton = new javax.swing.JButton();
        cancelJButton = new javax.swing.JButton();
        deleteUserJButton = new javax.swing.JButton();
        userPasswordJPanel = new javax.swing.JPanel();
        currentPasswordJText = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        newPasswordJText = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        confirmNewPasswordJText = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Super Logiciel inc.");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
        jLabel1.setText("Gestion des usagers");

        jLabel2.setText("Rechercher ");

        usersJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        usersJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(usersJList);

        userDetailsJPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        userDetailsJPanel.setToolTipText("Identification");

        firstnameJText.setName("Nom"); // NOI18N

        jLabel11.setText("Nom");

        lastnameJText.setName("Prénom"); // NOI18N

        jLabel12.setText("Prénom");

        usernameJText.setName("Nom d'utilisateur"); // NOI18N

        jLabel13.setText("Nom d'utilisateur");

        emailJText.setName("Courriel"); // NOI18N

        jLabel14.setText("Courriel");

        roleJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel15.setText("Rôle");

        javax.swing.GroupLayout userDetailsJPanelLayout = new javax.swing.GroupLayout(userDetailsJPanel);
        userDetailsJPanel.setLayout(userDetailsJPanelLayout);
        userDetailsJPanelLayout.setHorizontalGroup(
            userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userDetailsJPanelLayout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addGroup(userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel13)
                    .addComponent(jLabel12)
                    .addComponent(jLabel11)
                    .addComponent(jLabel14)
                    .addComponent(jLabel15))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(emailJText, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                    .addComponent(usernameJText, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lastnameJText, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(firstnameJText)
                    .addComponent(roleJComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        userDetailsJPanelLayout.setVerticalGroup(
            userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userDetailsJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(firstnameJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lastnameJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(emailJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(roleJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel15))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        newUserJButton.setText("Nouveau");
        newUserJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newUserJButtonActionPerformed(evt);
            }
        });

        saveUserJButton.setText("Enregistrer");
        saveUserJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveUserJButtonActionPerformed(evt);
            }
        });

        cancelJButton.setText("Annuler");
        cancelJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelJButtonActionPerformed(evt);
            }
        });

        deleteUserJButton.setText("Supprimer");
        deleteUserJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteUserJButtonActionPerformed(evt);
            }
        });

        userPasswordJPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        currentPasswordJText.setEditable(false);
        currentPasswordJText.setFocusable(false);

        jLabel8.setText("Mot de passe courant");

        newPasswordJText.setName("Nouveau mot de passe"); // NOI18N

        jLabel9.setText("Nouveau mot de passe");

        confirmNewPasswordJText.setName("Confirmation du mot de passe"); // NOI18N

        jLabel10.setText("Confirmation");

        javax.swing.GroupLayout userPasswordJPanelLayout = new javax.swing.GroupLayout(userPasswordJPanel);
        userPasswordJPanel.setLayout(userPasswordJPanelLayout);
        userPasswordJPanelLayout.setHorizontalGroup(
            userPasswordJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userPasswordJPanelLayout.createSequentialGroup()
                .addGroup(userPasswordJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(userPasswordJPanelLayout.createSequentialGroup()
                        .addGap(48, 48, 48)
                        .addComponent(jLabel9))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, userPasswordJPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(userPasswordJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userPasswordJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(currentPasswordJText)
                    .addComponent(newPasswordJText)
                    .addComponent(confirmNewPasswordJText, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        userPasswordJPanelLayout.setVerticalGroup(
            userPasswordJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(userPasswordJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(userPasswordJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(currentPasswordJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(userPasswordJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newPasswordJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addGap(12, 12, 12)
                .addGroup(userPasswordJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmNewPasswordJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 246, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(userSearchJText))
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(newUserJButton)
                        .addGap(18, 18, 18)
                        .addComponent(deleteUserJButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(saveUserJButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelJButton))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(userPasswordJPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(userDetailsJPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(userSearchJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(userDetailsJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(userPasswordJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(newUserJButton)
                            .addComponent(saveUserJButton)
                            .addComponent(cancelJButton)
                            .addComponent(deleteUserJButton)))
                    .addComponent(jScrollPane1))
                .addContainerGap(48, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelJButtonActionPerformed
       
        userSelected(null, false);
    }//GEN-LAST:event_cancelJButtonActionPerformed

    private void saveUserJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveUserJButtonActionPerformed
       
        save();
    }//GEN-LAST:event_saveUserJButtonActionPerformed

    private void deleteUserJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteUserJButtonActionPerformed
        
        delete();
    }//GEN-LAST:event_deleteUserJButtonActionPerformed

    private void newUserJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newUserJButtonActionPerformed
        
        usersJList.clearSelection();
        firstnameJText.requestFocus();
        
        isNewUser = true;
        userSelected(new Usager(), true);
    }//GEN-LAST:event_newUserJButtonActionPerformed

    private final DocumentListener firstnameDocumentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
        }

        private void updateSaveStatus() 
        {
            setMustSave(!firstnameJText.getText().equals(selectedUser.getFirstname()));
        }
    };
    
    private final DocumentListener lastnameDocumentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
        }

        private void updateSaveStatus() 
        {
            setMustSave(!lastnameJText.getText().equals(selectedUser.getLastname()));
        }
    };
    
    private final DocumentListener usernameDocumentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
        }

        private void updateSaveStatus() 
        {
            setMustSave(!usernameJText.getText().equals(selectedUser.getUsername()));
        }
    };
    
    private final DocumentListener emailDocumentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
        }

        private void updateSaveStatus() 
        {
            setMustSave(!emailJText.getText().equals(selectedUser.getEmail()));
        }
    };
    
    private class ItemChangeListener implements ItemListener
    {
        @Override
        public void itemStateChanged(ItemEvent evt) 
        {
            if (evt.getStateChange() == ItemEvent.SELECTED && selectedUser != null) 
            {
                Role item = (Role)evt.getItem();
                
                setMustSave((item != selectedUser.getRole()));
            }
        }
    }
    
    private final DocumentListener passwordModificationDocumentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
        }
        
        private void updateSaveStatus() 
        {
            setMustSave(true);
        }
    };
        
    private final DocumentListener searchDocumentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            launchSearch(userSearchJText.getText());
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            launchSearch(userSearchJText.getText());
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
            launchSearch(userSearchJText.getText());
        }
        
    };
    
    private final ListSelectionListener listSelectItemListener = new ListSelectionListener() 
    {
        @Override
        public void valueChanged(ListSelectionEvent evt) 
        {
            if(!evt.getValueIsAdjusting())
            {
                int selectedIndex = usersJList.getSelectedIndex();
                
                if(selectedIndex != -1)
                    userSelected((Usager)(usersListModel.get(selectedIndex)), false);
            }
        }
    };
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelJButton;
    private javax.swing.JTextField confirmNewPasswordJText;
    private javax.swing.JTextField currentPasswordJText;
    private javax.swing.JButton deleteUserJButton;
    private javax.swing.JTextField emailJText;
    private javax.swing.JTextField firstnameJText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField lastnameJText;
    private javax.swing.JTextField newPasswordJText;
    private javax.swing.JButton newUserJButton;
    private javax.swing.JComboBox roleJComboBox;
    private javax.swing.JButton saveUserJButton;
    private javax.swing.JPanel userDetailsJPanel;
    private javax.swing.JPanel userPasswordJPanel;
    private javax.swing.JTextField userSearchJText;
    private javax.swing.JTextField usernameJText;
    private javax.swing.JList usersJList;
    // End of variables declaration//GEN-END:variables

    private void launchSearch(String criteria) 
    {
        usersListModel.clear();
        ArrayList<Usager> usersToShow;
        
        if(!criteria.isEmpty())
            usersToShow = findUsager(criteria);
        else
            usersToShow = CatalogueUsagers.getInstance().getAll();
        
        for(Usager u : usersToShow)
                    usersListModel.addElement(u);
    }

    private ArrayList<Usager> findUsager(String criteria) 
    {   
        return CatalogueUsagers.getInstance().find(criteria);
    }
    
    private void userSelected(Usager user, boolean isNew)
    {
        if(verifySaveStatus())
        {      
            removeDataChangeListeners();

            isNewUser = isNew;
            selectedUser = user;

            if(selectedUser == null)
            {
                usersJList.clearSelection();

                clearFields();
                setFieldsEnabled(false);
                setButtonsEnabled(true , false, false, false);
            }
            else
            {
                setFieldsValue(selectedUser);

                if(selectedUser.isActivated())
                    setDataChangeListeners();

                setFieldsEnabled(true && selectedUser.isActivated());
                setButtonsEnabled(true && selectedUser.isActivated(), true && selectedUser.isActivated(), false, true);
            }
        }
    }

    private void setFieldsEnabled(boolean enabled) 
    {
        firstnameJText.setEditable(enabled);
        lastnameJText.setEditable(enabled);
        emailJText.setEditable(enabled);
        usernameJText.setEditable(enabled);
        
        roleJComboBox.setEnabled(enabled);
        
        newPasswordJText.setEditable(enabled);
        confirmNewPasswordJText.setEditable(enabled);
    }

    private void setButtonsEnabled(boolean buttonNew, boolean buttonDelete, boolean buttonSave, boolean buttonCancel) 
    {
        newUserJButton.setEnabled(buttonNew);
        deleteUserJButton.setEnabled(buttonDelete);
        saveUserJButton.setEnabled(buttonSave);
        cancelJButton.setEnabled(buttonCancel);
    }
        
    private void clearFields() 
    {
        firstnameJText.setText("");
        lastnameJText.setText("");
        emailJText.setText("");
        usernameJText.setText("");
        
        roleJComboBox.setSelectedIndex(0);
        
        currentPasswordJText.setText("");
        newPasswordJText.setText("");
        confirmNewPasswordJText.setText("");
    }

    private void setFieldsValue(Usager selectedUser) 
    {
        firstnameJText.setText(selectedUser.getFirstname());
        lastnameJText.setText(selectedUser.getLastname());
        emailJText.setText(selectedUser.getEmail());
        usernameJText.setText(selectedUser.getUsername());
        
        roleJComboBox.setSelectedItem(selectedUser.getRole());
        
        currentPasswordJText.setText(selectedUser.getPassword());
        newPasswordJText.setText("");
        confirmNewPasswordJText.setText("");
    }
    
    private void setDataChangeListeners()
    {
        firstnameJText.getDocument().addDocumentListener(firstnameDocumentListener);
        lastnameJText.getDocument().addDocumentListener(lastnameDocumentListener);
        usernameJText.getDocument().addDocumentListener(usernameDocumentListener);
        emailJText.getDocument().addDocumentListener(emailDocumentListener);
        
        roleJComboBox.addItemListener(roleSelectionChange);
        
        newPasswordJText.getDocument().addDocumentListener(passwordModificationDocumentListener);
        confirmNewPasswordJText.getDocument().addDocumentListener(passwordModificationDocumentListener);
    }
    
    private void removeDataChangeListeners()
    {
        firstnameJText.getDocument().removeDocumentListener(firstnameDocumentListener);
        lastnameJText.getDocument().removeDocumentListener(lastnameDocumentListener);
        usernameJText.getDocument().removeDocumentListener(usernameDocumentListener);
        emailJText.getDocument().removeDocumentListener(emailDocumentListener);
        
        roleJComboBox.removeItemListener(roleSelectionChange);
        
        newPasswordJText.getDocument().removeDocumentListener(passwordModificationDocumentListener);
        confirmNewPasswordJText.getDocument().removeDocumentListener(passwordModificationDocumentListener);
    }
    
    private void setMustSave(boolean status) 
    {
        mustSave = status;

        saveUserJButton.setEnabled(mustSave);
        
        userSearchJText.setEnabled(!status);
        usersJList.setEnabled(!status);
    }
    
    private boolean save() 
    {
        if(fieldsAreValid())
        {
            if(CatalogueUsagers.getInstance().usernameAlreadyExistsExcludeUser(usernameJText.getText(), selectedUser))
            {
                JOptionPane.showMessageDialog(this, "Le nom d'utilisateur " + usernameJText.getText() +" existe déjà!", "Erreur!", JOptionPane.ERROR_MESSAGE);
                return false;
            }
            
            copyFieldsToUser();
            
            if(isNewUser)
            {
                CatalogueUsagers.getInstance().add(selectedUser);
                usersListModel.addElement(selectedUser);
                
                isNewUser = false;
            }
            
            currentPasswordJText.setText(selectedUser.getPassword());
            usersJList.updateUI();
            setMustSave(false);
            
            return true;
        }
        else
            return false;
    }
    
    private boolean askForConfirmation(String message) 
    {
        int dialogResult = JOptionPane.showConfirmDialog(this, message, "Attention", JOptionPane.YES_NO_OPTION);
        
        return dialogResult == 0;//Si == 0 -> oui
    }
    
    
    private boolean verifySaveStatus()//Retourne TRUE si la sauvegarde a fonctionnnée ou n'avait pas besoin de sauvegarder et FALSE si la sauvegarde a échoué
    {
        if(mustSave && askForConfirmation("Voulez-vous sauvegarder les changements effectués?"))
        {
            return save();
        }
        else
        {
            setMustSave(false);
            
            return true;
        }
    }
    
    private boolean fieldsAreValid() 
    {
        ArrayList<JTextField> jTexts = new ArrayList<>(Arrays.asList(new JTextField[]{ firstnameJText, lastnameJText, usernameJText, emailJText}));
        
        if(isNewUser)
        {
            jTexts.add(newPasswordJText);
            jTexts.add(confirmNewPasswordJText);
        }
        
        String errorMessage = "";
        
        for(JTextField jTxt : jTexts)
        {
            if(stringIsEmptyOrSpaces(jTxt.getText()))
            {
                errorMessage += "Le champ " + jTxt.getName() + " ne peut être vide!\n";
            }     
        }
        
        
        if(!stringIsEmptyOrSpaces(newPasswordJText.getText()) || !stringIsEmptyOrSpaces(confirmNewPasswordJText.getText()) || isNewUser)
        {
            if(!newPasswordJText.getText().equals(confirmNewPasswordJText.getText()))
            {
                errorMessage += "Les champs " + newPasswordJText.getName() + " et "+ confirmNewPasswordJText.getName() + " doivent être identiques!\n";
            }
        }
        
        if(!errorMessage.equalsIgnoreCase(""))
        {
            JOptionPane.showMessageDialog(this, errorMessage, "Erreur!", JOptionPane.ERROR_MESSAGE);
        }
        
        return errorMessage.equalsIgnoreCase("");
    }
    
    private void copyFieldsToUser() 
    {
        selectedUser.setFirstname(firstnameJText.getText());
        selectedUser.setLastname(lastnameJText.getText());
        
        selectedUser.setUsername(usernameJText.getText());
        
        selectedUser.setEmail(emailJText.getText());
        
        selectedUser.setRole((Role)roleJComboBox.getSelectedItem());
        
        selectedUser.setPassword(confirmNewPasswordJText.getText());
    }
    
    private boolean stringIsEmptyOrSpaces(String value)
    {
        return value.isEmpty() || value.replace(" ", "").isEmpty();
    }
    
    private void delete() 
    {
        if(askForConfirmation((CatalogueUsagers.getInstance().userHasSales(selectedUser) ? "Êtes-vous sûr de vouloir désactiver cet usager?" : "Êtes-vous sûr de vouloir supprimer cet usager?")))
        {
            if(!isNewUser)
            {
                if(selectedUser == this.usager)
                {
                    JOptionPane.showMessageDialog(this, "Vous ne pouvez pas vous supprimer vous-même!", "Erreur!", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if(CatalogueUsagers.getInstance().delete(selectedUser))
                {
                    usersListModel.removeElement(selectedUser);              
                }

                usersJList.updateUI();
            }

            setMustSave(false);
            userSelected(null, false);
        }
    }
}
